import { Ref, toRefs } from 'vue';

interface WatermarkOptions {
    waterStrText: string;
    containerRef: Ref<HTMLElement | null>;
    canvasWidth: number;
    canvasHeight: number;
    waterFont: string;
    waterfillStyle: string;
}

export const getmark = () => {
    // 绘制函数
    const setWatermark = (options: WatermarkOptions) => {
        const { containerRef } = toRefs(options)
        const { waterStrText, canvasWidth, canvasHeight, waterFont, waterfillStyle } = options;
        const id = "water_mark_id";
        const existingWatermark = document.getElementById(id);
        if (existingWatermark !== null && containerRef.value) {
            containerRef.value.removeChild(existingWatermark);
        }

        const can = document.createElement("canvas");
        can.width = canvasWidth || 150;
        can.height = canvasHeight || 120;
        const cans = can.getContext("2d")!;
        cans.rotate((-10 * Math.PI) / 180);
        cans.font = waterFont || "16px Vedana";
        cans.fillStyle = waterfillStyle || "rgba(200, 200, 200, 0.80)";
        cans.textAlign = "left";
        cans.fillText(waterStrText, can.width / 10, can.height / 4);

        const div = document.createElement("div");
        div.id = id;
        div.style.pointerEvents = "none";
        div.style.position = "absolute";
        div.style.zIndex = "10";
        div.style.width = `${containerRef.value?.clientWidth || 0}px`;
        div.style.height = `${containerRef.value?.clientHeight || 0}px`;
        div.style.background = `url(${can.toDataURL("image/png")}) left top repeat`;
        if (containerRef.value) {
            containerRef.value.appendChild(div);
        }
    };

    const watermark = (options: WatermarkOptions) => {
        // 调用绘制函数
        setWatermark(options);
        // 窗口变动,重新绘制
        window.onresize = () => {
            if (options.containerRef) {
                setWatermark(options);
            }
        };
    };

    return { watermark };
};